<template>
<div>
  count:{{count}}
  <br />
  text:{{text}}
  <br />
 <input v-model="text" />
</div>

</template>

<script lang="ts">
import { ref,unref,toRef,toRefs,isRef,customRef,reactive,shallowRef,isReactive,watchEffect,triggerRef} from 'vue'
function useFeatureX() {
  const state = reactive({
    foo: 1,
    bar: 2
  })



  // logic operating on state

  // convert to refs when returning
  return toRefs(state)
}
export default {
  
  setup() {
      const count = ref(0)
        console.log(count.value) // 0
        count.value++
        console.log(count.value) // 1

        //unref语法糖：val = isRef(val) ? val.value : val
        const uncount = unref(count) 
        console.log("unref:"+uncount) // 1


        const state = reactive({
            foo: 1,
            bar: 2
        })

        //toRef相当于reactive内值的另一个别称
        const fooRef = toRef(state, 'foo')

        fooRef.value++
        console.log(state.foo) // 2

        state.foo++
        console.log(fooRef.value) // 3

        //toRefs批量转换成ref
        const stateAsRefs = toRefs(state)
        state.foo++
        console.log(stateAsRefs.foo.value) // 4

        stateAsRefs.foo.value++
        console.log(state.foo) // 5
        const { foo, bar } = useFeatureX();//


        //是否是ref
        console.log("isRef(count):",isRef(count))
        console.log("isRef(state):",isRef(state))

        // 创建浅层的 ref
        const shallowReffoo = shallowRef({})
        console.log(isReactive(shallowReffoo.value)) // false
        // 更改对操作会触发响应
        shallowReffoo.value = {}
        // 但上面新赋的这个对象并不会变为响应式对象
        console.log(isReactive(shallowReffoo.value)) // false


        const shallow = shallowRef({
            greet: 'Hello, world'
        })

        // Logs "Hello, world" once for the first run-through
        watchEffect(() => {
            console.log("shallow.value.greet=====>",shallow.value.greet)
        })

        // This won't trigger the effect because the ref is shallow
        shallow.value.greet = 'Hello, universe'

        //triggerRef触发响应
        // Logs "Hello, universe"
        triggerRef(shallow);



   
    function useDebouncedRef(value: string, delay = 1200) {
        let timeout: any
        return customRef((track, trigger) => {
            return {
            get() {
                track()//跟踪
                return value
            },
            set(newValue) {
                clearTimeout(timeout)
                timeout = setTimeout(() => {
                value = newValue as string
                trigger()//响应dom
                }, delay)
            }
            }
        })
        }

    return {
        count,
        foo, 
        bar,
        text:useDebouncedRef('hello')
    }
  },
}
</script>